package imdbfolder.data;

import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;

public class JPEGWriter {
    public static void write(RenderedImage image, float quality, File file) throws IOException {
        ImageWriter writer = null;
        Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("JPEG");

        if (!iter.hasNext()) {
            throw new IOException("No Writers Available");
        }
        writer = iter.next();

        if (file.exists()) {
            file.delete();
        }

        ImageOutputStream ios = ImageIO.createImageOutputStream(file);
        writer.setOutput(ios);

        JPEGImageWriteParam iwp = new JPEGImageWriteParam(null);
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(quality);

        writer.write(null, new IIOImage(image, null, null), iwp);

        ios.flush();
        writer.dispose();
        ios.close();
    }
}
